import React from 'react'
import {withRouter} from 'react-router-dom'
import UrlPattern from 'url-pattern'
import {Form, Input, Checkbox, Row, Col, Tooltip, Icon} from 'antd'
import {connect} from 'react-redux'
import {formItemLayout, mdLayout} from '../../constant/constant-style'
import * as actions from '../../actions/multiple-choice-quiz'
import SelectTags from '../common/select-tags'
import {TwsReactMarkdownEditor} from 'tws-antd'
import ButtonGroup from '../common/button-group'
import {MULTIPLE_CHOICE} from '../../constant/quiz-type'
import * as cache from '../../constant/cache-quiz'

import {getUploadUrl} from '../../constant/upload-url'
import { FormattedMessage } from 'react-intl'
import {convertContent} from "../../constant/lang-util";

const FormItem = Form.Item
const initQuiz = () =>  {
    return {
        choicesList: [
            {option: '', isChecked: false},
            {option: '', isChecked: false},
            {option: '', isChecked: false},
            {option: '', isChecked: false}
        ],
        errors: [false, false, false, false],
        description: '',
        tags: [],
        descriptionError: ''
    }
}

class AddOrEditMultipleChoiceQuizBody extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      id: -1,
      ...initQuiz()
    }
  }

  componentWillMount () {
    const pattern = new UrlPattern('/multipleChoiceQuizzes/:id/editor')
    const urlParams = pattern.match(this.props.location.pathname) || {id: -1}
    this.setState({id: parseInt(urlParams.id, 10)})
    let localStorageItem = cache.getItemFromLocalStorage(MULTIPLE_CHOICE, parseInt(urlParams.id, 10))
    if (localStorageItem) {
      this.setState({...localStorageItem})
      return
    }
    if (urlParams.id > 0) {
      this.props.getMultipleChoiceQuiz(parseInt(urlParams.id, 10))
    }
  }

  formatChoices = (multipleChoiceQuiz) => {
      let choicesList = [];
      multipleChoiceQuiz.choices.map((choice, index) => {
          return choicesList.push({option: choice, isChecked: multipleChoiceQuiz.answer.includes(index.toString())})
      })
      return choicesList
  }

  componentWillReceiveProps (nextProps) {
    const {multipleChoiceQuiz} = nextProps

    if (multipleChoiceQuiz && this.props.multipleChoiceQuiz !== multipleChoiceQuiz) {
      let {tags, description } = multipleChoiceQuiz
      let choicesList = this.formatChoices(multipleChoiceQuiz)
      tags = tags.map(tag => tag.name)
      this.setState({choicesList, description, tags})
    }
  }

  errorDisplay () {
    const {choicesList, errors, description} = this.state
    choicesList.forEach((choice, index) => {
      if (choice.option === '') {
        document.getElementById(`error${index}`).innerHTML = convertContent('请输入选项')
        errors[index] = true
        this.setState({errors})
      }
    })

    if (choicesList.every(choice => choice.isChecked===false)) {
      document.getElementById(`error`).innerHTML = convertContent('请选择答案')
    }

    if (description.length === 0) {
      this.setState({
        descriptionError: '请输入描述'
      })
    }

    const choices = this.formatChoicesAndAnswers(choicesList)
    const {answer} = choices
    return !errors.find(err => err) && description.length !== 0 && answer.length !== 0;
  }

  isError = () =>{
    const {choicesList, errors, description} = this.state
    const {answer}  = this.formatChoicesAndAnswers(choicesList)
    return errors.find(err => err) || description.length === 0 || answer.length === 0;
  }

  cleanStateOrBack (isBack) {
      isBack ? this.props.history.push('/multipleChoiceQuizzes') : this.setState({...initQuiz()})
  }

  formatChoicesAndAnswers = (choicesList) => {
    let answer = [];
    let options = [];
    choicesList.forEach((choice,index) => {
      if (choice.isChecked){
        answer.push(index.toString())
      }
    })
    choicesList.forEach((choice) => {
        options.push(choice.option)
    })
    return {options,answer}
  }

  handleSubmit(isBack) {
    if (this.isError()) {
      this.errorDisplay()
      return
    }

    const {choicesList, id, description, tags} = this.state
    const {options, answer} = this.formatChoicesAndAnswers(choicesList)
    const values = Object.assign({}, {choices: options, answer, description, tags})
    id > 0
      ? this.props.editMultipleChoiceQuiz(values, id, () => this.cleanStateOrBack(isBack))
      : this.props.addMultipleChoiceQuiz(values, () => this.cleanStateOrBack(isBack))

    cache.removeItemFromLocalStorage(MULTIPLE_CHOICE, id)
  }

  checkboxOnChange (index, e) {
    const {choicesList} = this.state
    document.getElementById(`error`).innerHTML = ''

    choicesList[index].isChecked = !!e.target.checked

    this.setState({
      choicesList
    }, () => cache.saveItemToLocalStorage(MULTIPLE_CHOICE, this.state))
  }

  optionOnChange (index, e) {
    const {choicesList, errors} = this.state
    const {value} = e.target
    document.getElementById(`error${index}`).innerHTML = ''

    if (choicesList.some(choice => choice.option === value) || value === '') {
      document.getElementById(`error${index}`).innerHTML =
        value === ''
            ? convertContent('请输入选项')
            : convertContent('选项重复，请重新填写')
      errors[index] = true
    } else {
      errors[index] = false
    }

    choicesList[index].option = e.target.value

    this.setState({
      choicesList,
      errors
    }, () => cache.saveItemToLocalStorage(MULTIPLE_CHOICE, this.state))
  }

  handleChange (description) {
    this.setState({description}, () => cache.saveItemToLocalStorage(MULTIPLE_CHOICE, this.state))
  }
  handleAddTags (tags) {
    this.setState({tags}, () => cache.saveItemToLocalStorage(MULTIPLE_CHOICE, this.state))
  }

  handleDeleteSelectItem(index){
    let {choicesList} = this.state
    choicesList = choicesList.filter((choice, idx) => index !== idx)
    this.setState({choicesList}, () => {
      cache.saveItemToLocalStorage(MULTIPLE_CHOICE, this.state)
    })
  }

  handleAddSelectItem(){
    let {choicesList} = this.state
    choicesList.push({option: '',isChecked: false})
    this.setState({choicesList}, () => cache.saveItemToLocalStorage(MULTIPLE_CHOICE, this.state))
  }

  render () {
    const {choicesList, errors, description, tags, descriptionError, id} = this.state
    const {settings} = this.props
    return (<Form>
      <p>
        <a onClick={() => window.history.back()}><Icon type='arrow-left' /><FormattedMessage id='返回上一页' /></a>
      </p>
      <FormItem
        {...mdLayout}
        label={<FormattedMessage id='题目描述' />}>
        <TwsReactMarkdownEditor
          action={getUploadUrl(settings.appContextPath)}
          value={description}
          onChange={this.handleChange.bind(this)} />
        <div style={{color: '#f5222d', lineHeight: '20px'}}>{descriptionError}</div>
      </FormItem>
      <FormItem
        {...formItemLayout}
        label={<FormattedMessage id='选项' />}
        required
            >
        {choicesList.map((choice,index) => {
          return (<Row key={index}>
            <Col span={2}>
              <Checkbox
                  onChange={this.checkboxOnChange.bind(this, index)}
                  checked={choice.isChecked}
              />
            </Col>
            <Col span={12}>
              <Row>
                <Col span={20}>
                  <Input
                      className={errors[index] ? 'input-error' : ''}
                      value={choicesList[index].option}
                      onChange={this.optionOnChange.bind(this, index)}
                  />
                </Col>
                <Col span={2}>
                  {index > 1 && this.state.id <= 0
                      ? <Tooltip title={<FormattedMessage id='删除选项'/>}>
                        <Icon type='minus-circle-o' style={operationStyle}
                              onClick={this.handleDeleteSelectItem.bind(this, index)}/>
                      </Tooltip>
                      : ''}
                </Col>
              </Row>
              <div style={{color: '#f5222d', lineHeight: '20px'}} id={`error${index}`} />
            </Col>
          </Row>)
        })}
        <div style={{color:'#f5222d', lineHeight: '20px'}} id={`error`} />
        {this.state.id <= 0
            ? <Tooltip title={<FormattedMessage id='添加一个选项'/>}>
              <Icon type='plus-circle-o' style={operationStyle} onClick={this.handleAddSelectItem.bind(this)}/>
            </Tooltip>
            : ''
        }
      </FormItem>
      <SelectTags
        addTags={this.handleAddTags.bind(this)}
        currentTags={tags}
            />
      <FormItem wrapperCol={{offset: 9}}>
        <ButtonGroup handleSubmit={this.handleSubmit.bind(this)} id={id} />
      </FormItem>
    </Form>)
  }
}

const operationStyle = {
  fontSize: '20px',
  marginLeft: '10px',
  cursor: 'pointer'

}

const mapStateToProps = (state) => ({
  multipleChoiceQuiz: state.multipleChoice.quiz,
  settings: state.settings
})

const mapDispatchToProps = dispatch => ({
  addMultipleChoiceQuiz: (quiz, callback) => dispatch(actions.addQuiz(quiz, callback)),
  getMultipleChoiceQuiz: (quizId) => dispatch(actions.getQuiz(quizId)),
  editMultipleChoiceQuiz: (quiz, id, callback) => dispatch(actions.editQuiz(quiz, id, callback))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Form.create()(AddOrEditMultipleChoiceQuizBody)))
